import { mapMutations, mapActions, mapState } from "vuex";
import _ from "lodash";
import { typeClassName } from "@/pages/config/classNameMap";
import dayjs from "dayjs";

const requireComponent = require.context("./", true, /[A-Z]\w+\.(vue)$/);
const comp = {};
requireComponent.keys().forEach((fileName) => {
  if (fileName != "./index.vue") {
    const componentConfig = requireComponent(fileName);
    const name = componentConfig.default.name;
    const componentName = _.camelCase(
      name
        .split("/")
        .pop()
        .replace(/\.\w+$/, "")
    );
    comp[componentName] = componentConfig.default || componentConfig;
  }
});
Object.keys(comp).map((key) => {
  comp[key].components = comp;
});
export default {
  components: comp,
  provide() {
    return {
      anc: this,
    };
  },
  computed: {},
  watch: {},
  created() {
    Object.keys(this.models).map((k) => {
      this.models[k].clz = this.$modelObject.create(this.models[k].modelType);
      this.models[k].clzs = this.$modelObject.create(
        this.models[k].modelType + "Collection"
      );
    });
  },
  mounted() {
    this.watchs.map((item) => {
      this.$watch(item.target, item.fn, { deep: item.deep });
    });
    this.$nextTick(() => {
      this.unwatch = this.$watch("vms", (newValue, oldValue) => {
        let flag = true;
        Object.keys(comp).map((k) => {
          if (!Object.keys(this.vms).includes(k)) {
            flag = false;
          }
        });
        this.completeLoad = flag;
      });
      if (process.env.NODE_ENV === "development") {
        this.init();
        console.log({
          me: this,
          vms: this.vms,
          completeLoad: this.completeLoad,
        });
      }
    });
  },
  destroyed() {
    this.unwatch();
  },
  data() {
    return {
      vms: {}, //页面组件vue实例
      completeLoad: false, //验证所有元素是否全部加载完成
      me: this,
      watchs: [],
      models: {
        //模型
        main: { ...typeClassName["salesOrder"] },
        second: { ...typeClassName["salesOrder"] },
        third: { ...typeClassName["salesOrder"] },
        fourth: { ...typeClassName["salesOrder"] },
      },
      isAbled: true,
      dataSet: {
        //数据集
        mainData: [],
        secondData: [],
        thirdData: [],
        fourthData: [],
        formData: {},
        workReport: {},
        workUnitData: {},
      },
      selfFilter: {
        orderFrom: "合批订单",
      },
      currentTab: "main",
      hierOptions: [],
      productOptions: [],
      locationOptions: [],
    };
  },
  methods: {
    init() {
      this.getProduct();
    },
    changeTabs(name) {
      if (name == 0) {
        this.selfFilter.orderFrom = "合批订单";
        this.currentTab = "main";
      } else if (name == 1) {
        this.selfFilter.orderFrom = "钨粉";
        this.currentTab = "second";
      } else if (name == 2) {
        this.selfFilter.orderFrom = "碳化钨";
        this.currentTab = "third";
      } else {
        this.selfFilter.orderFrom = "库存订单";
        this.currentTab = "fourth";
      }
      this.vms[this.currentTab + "Table"].attrs.pageNavigation.pageNumber = 1;
      this.loadPage(
        this.vms[this.currentTab + "Table"].attrs.pageNavigation,
        {}
      );
      this.isAbled = name != 3 ? true : false;
    },
    /**
     *
     * @param {分页} pageNavigation
     * @param {筛选条件} filter
     * @param {*} orderBy
     * 页面加载方法
     */
    loadPage(pageNavigation, filter) {
      let newFilter = {
        ...filter,
        className: this.models[this.currentTab].className,
        type: this.models[this.currentTab].type,
        ...this.selfFilter,
      };
      this.vms[this.currentTab + "Table"].attrs.loading = true;
      this._$queryByPage(
        this.models[this.currentTab].clzs,
        pageNavigation,
        newFilter,
        "",
        "",
        false
      ).then((res) => {
        this.vms[this.currentTab + "Table"].attrs.loading = false;
        // 整理数据 数据格式
        this.dataSet[this.currentTab + "Data"] =
          this.models[this.currentTab].clzs.valueRecords;
      });
      this.vms[this.currentTab + "Table"].attrs.loading = false;
    },
    /**
     * 新增弹窗
     */
    handleCreate() {
      this._modalShow("createModal");
      this.dataSet.formData = this.$modelObject.getTpl(
        this.models[this.currentTab].modelType
      ); // 这是一个整理接口数据JSON格式的方法
    },
    /**
     *查看弹窗
     * @param {*} row
     *
     */
    handleDetail(row) {
      this.dataSet.formData = row;
      this._modalShow("detailModal");
    },
    /**
     *编辑弹窗
     * @param {*} row
     *
     */
    handleEdit(row) {
      this._modalShow("editModal");
      this.dataSet.formData = row;
    },
    /**
     * 删除行数据
     * @param {行数据} row
     * @param {索引} index
     */
    handleDelete(row, index) {
      this._$deleteConfirm(() => {
        this._$deleteByIds(this.models[this.currentTab].clzs, [row.id]).then(
          (res) => {
            this.vms[
              this.currentTab + "Table"
            ].attrs.pageNavigation.pageNumber = 1;
            this.loadPage(
              this.vms[this.currentTab + "Table"].attrs.pageNavigation,
              {}
            );
          }
        );
      });
    },

    /**
     * 多选删除
     * @param {行数据} selection
     */
    handleDeleteMultiple(selection) {
      this._$deleteConfirm(() => {
        let ids = selection.map((items) => String(items.id));
        this._$deleteByIds(this.models[this.currentTab].clzs, ids).then(
          (res) => {
            this.vms[this.currentTab + "Table"].pageNavigation.pageNumber = 1;
            this.loadPage(
              this.vms[this.currentTab + "Table"].pageNavigation,
              {}
            );
          }
        );
      });
    },
    // 新增确认 
    createModalOk(btn) {
      this._$validateAll([this.vms.createView], (valid) => {
        if (valid) {
          this.dataSet.formData.values.orderFrom = this.selfFilter.orderFrom;
          this._merge(this.dataSet.formData, {
            className: this.models[this.currentTab].className,
            type: this.models[this.currentTab].type,
            name: dayjs().valueOf(),
          });
          this.models[this.currentTab].clz
            .add(this.dataSet.formData)
            .then((flag) => {
              if (flag) {
                this._modalClose("createModal");
                this._resetForm("createView");
                btn.loading = false;
                this.vms[
                  this.currentTab + "Table"
                ].attrs.pageNavigation.pageNumber = 1;
                this.loadPage(
                  this.vms[this.currentTab + "Table"].attrs.pageNavigation,
                  {}
                );
              }
            });
        } else {
          btn.loading = false;
          this.$Message.info("请填写必填内容");
        }
      });
    },
    // 编辑确认
    editModalOk(btn) {
      this.vms.editView.validate((valid) => {
        if (valid) {
          this.models[this.currentTab].clz.setRecord(this.dataSet.formData);
          this.models[this.currentTab].clz.updateById().then((flag) => {
            if (flag) {
              this._modalClose("editModal");
              btn.loading = false;
              this._resetForm("editView");
              this.loadPage(
                this.vms[this.currentTab + "Table"].pageNavigation,
                {}
              );
            } else {
              this._modalClose("editModal");
            }
          });
        } else {
          btn.loading = false;
          this._$requireInfo();
        }
      });
    },
    getProduct() {
      let data = {
        type: "material",
        className: "MaterialDetail",
      };
      this.$api.ResourceInstance.query(data)
        .then((res) => {
          console.log(res);
          // this.dataSet.routing = res.data.data.records;
          this._$getOptions(res, "productOptions");
        })
        .catch((err) => {
          console.log(err);
        });
    },

    /****************工具***************/
    _getModelFields(name, ...args) {
      let map = {};
      args.map((key) => {
        map[key] = this.models[name][key];
      });
      return map;
    },
    _getModelRecord(name) {
      return this.models[name].clz.record;
    },
    _setVmValue(name, key, value) {
      _.set(this.vms[name], key, value);
    },
    _getModelTpl(name) {
      return this.$modelObject.getTpl(this.models[name].modelType);
    },
    _setDataSet(name, data) {
      this.dataSet[name] = data;
    },
    _modalShow(name) {
      _.set(this.vms[name], "config.show", true);
    },
    _modalClose(name) {
      _.set(this.vms[name], "config.show", false);
      _.set(this.vms[name], "config.loading", false);
    },
    _tableLoading(name) {
      _.set(this.vms[name], "loading", true);
    },
    _tableUnLoading(name) {
      _.set(this.vms[name], "loading", false);
    },
    _resetForm(name) {
      this.vms[name].resetFields();
    },
  },
};
